<template>
  <el-select
    filterable
    v-model="biotopeId"
    :filter-method="searchBiotope"
    @change="getBiotopeId"
    v-loadmore="getMoreData"
    placeholder="请选择小区" clearable>
    <el-option label="全部" value="" v-if="isDefault"></el-option>
    <el-option
      v-for="(item,index) in biotopeOption"
      :key="index"
      :label="item.name+'('+item.higherAddress+')'"
      :value="item.id">
    </el-option>
  </el-select>
</template>

<script>

import {getBiotopeByName} from "../../api/biotope";

export default {
  // bId:小区id回显
  props:['bId','isDefault'],
  data() {
    return {
      page:1,
      limit:10,
      hasMore:true,
      biotopeId:'',
      biotopeOption:[],
      keyword: '',
    }
  },
  mounted() {
    this.getBiotopeInfo();
  },
  methods: {
    searchBiotope(e){
      this.hasMore = true;
      this.page = 1;
      this.keyword = e;
      this.biotopeOption = [];
      this.getBiotopeInfo();
    },

    getMoreData(){
      let that = this;
      if (that.hasMore) {
        that.getBiotopeInfo();
      }
    },

    getBiotopeInfo(){
      let that = this;
      let param = {
        limit:that.limit,
        page:that.page,
        name:that.keyword,
      }
      getBiotopeByName(param).then(res=>{
        if (res.success) {
          if (that.isDefault&&!this.bId){
            that.biotopeId = res.data[0].id;
            that.$emit('listenToBiotope',that.biotopeId);
          }
          that.initData(res.data);
        } else {
          that.hasMore = false;
        }
      }).catch((e)=>{
        that.hasMore = false;
      })
    },

    // 初始化数据
    initData(e) {
      let list = this.biotopeOption;
      let data = e;
      list ? list = list.concat(data) : list = data;
      this.biotopeOption = list;
      this.hasMore = e.length === this.limit;
      this.page = this.page += 1;
    },

    getBiotopeId(val){
      this.$emit('listenToBiotope',val?val:'');
    }
  },
  watch:{
    bId(newV,oldV){
      this.biotopeId = this.bId;
    },
  }
}
</script>

<style scoped>
.area_item span{
  font-size: 14px;
  margin-right: 10px;
}
</style>
